<script setup>

import { ref } from 'vue'
import { roomListService } from '@/api/room.js'
import { addRoomBookService } from '@/api/book.js'

import { ElMessage, ElMessageBox } from 'element-plus'
import useUserInfoStore from '@/stores/userInfo.js'
import {useRouter} from 'vue-router'

// 初始化路由和用户信息
const router = useRouter()
const userInfoStore = useUserInfoStore();
const userInfo = ref({...userInfoStore.info})  // 获取当前登录用户信息

//列表数据相关
const dataInfo = ref([])  // 会议室列表数据

//分页相关参数
const pageNum = ref(1)  // 当前页码
const total = ref(20)   // 总记录数
const pageSize = ref(10)  // 每页显示条数

//分页大小改变时的处理函数
const onSizeChange = (size) => {
  pageSize.value = size
  getList()  // 重新获取列表数据
}

//当前页码改变时的处理函数
const onCurrentChange = (num) => {
  pageNum.value = num
  getList()  // 重新获取列表数据
}

// 搜索表单数据
const searchData = ref({
  roomname: '',  // 会议室名称
  capacity: ''   // 容纳人数
});

// 搜索表单引用
const searchFormRef = ref();

// 重置搜索表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()  // 清空表单字段
}

//获取会议室列表数据
const getList = async () => {
  // 构建查询参数
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    roomname: (searchData.value.roomname || '').trim() || null,
    capacity: searchData.value.capacity || null
  }
  // 调用会议室列表服务
  let result = await roomListService(params);

  //更新视图数据
  total.value = result.data.total;
  let items = result.data.items || [];

  // 根据容纳人数进行筛选
  if (searchData.value.capacity) {
    items = items.filter(item => {
      const cap = parseInt(item.capacity);
      const searchCap = parseInt(searchData.value.capacity);
      if (searchCap === 51) {
        return cap >= 50;  // 50人以上
      } else if (searchCap === 50) {
        return cap >= 30 && cap <= 50;  // 30-50人
      } else if (searchCap === 30) {
        return cap >= 10 && cap <= 30;  // 10-30人
      } else {
        return cap < 10;  // 10人以下
      }
    });
  }

  dataInfo.value = items;
};

// 初始化时获取列表数据
getList();

// 导入会议室工具函数
import { createRoomTool } from '@/utils/common.js'

//预约表单数据模型
const addOrEditModel = ref({
  ...createRoomTool(),
  title: '',        // 活动名称
  reason: '',       // 预约理由
  description: ''   // 活动描述
});

//控制预约弹窗显示
const dialogVisible = ref(false);
//弹窗标题
const title = ref('');
//预约窗口状态
const isOpenBookWindow = ref(true);
//表单引用
const ruleFormRef = ref();

//表单校验规则
const rules = {
  timeslot: [
    { required: true, message: '请输入预约时间', trigger: 'blur' },
  ]
}

//显示预约弹窗
const showDialog = (row) => {
  dialogVisible.value = true;
  title.value = '预约信息'
  //复制会议室信息到表单
  addOrEditModel.value = {...row};
}

// 处理预约提交
const handleBook = async() => {
  // 构建预约参数
  const params = {
    roomid: addOrEditModel.value.id,
    bookstate: '已预约',
    state: '待审批',
    bookerid: userInfo.value.id,
    startTime: addOrEditModel.value.timeslot[0],
    endTime: addOrEditModel.value.timeslot[1],
    title: addOrEditModel.value.title,
    reason: addOrEditModel.value.reason,
    description: addOrEditModel.value.description
  };

  try {
    // 调用预约服务
    let result = await addRoomBookService(params);
    if(result?.code === 0) {
      ElMessage.success('预约成功')
      dialogVisible.value = false;
      router.push('/room/bookApprove')  // 跳转到预约审批页面
    } else if (result?.code === 1) {
      dialogVisible.value = false;
      ElMessage.warning(result.message);  // 显示预约冲突提示
    } else {
      ElMessage.error('预约失败')
    }
  } catch (error) {
    if (error.code === 1) {
      dialogVisible.value = false;
      ElMessage.warning(error.message);
    } else {
      ElMessage.error('服务异常，请稍后再试');
    }
  }
}

// 时间验证函数
const validateTimes = () => {
  const now = new Date();
  const startTime = new Date(addOrEditModel.value.timeslot[0]);
  const endTime = new Date(addOrEditModel.value.timeslot[1]);

  // 检查是否预约过去的时间
  if (startTime < now.setHours(0, 0, 0, 0)) {
    dialogVisible.value = false;
    ElMessage.warning('时间填写错误：不能预约本日之前的会议室');
    return false;
  }

  // 检查结束时间是否早于开始时间
  if (endTime <= startTime) {
    dialogVisible.value = false;
    ElMessage.warning('时间填写错误：结束时间不能在开始时间之前');
    return false;
  }

  return true;
};

// 提交表单
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid && validateTimes()) {
      handleBook();
    }
  });
};

</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header" style="text-align: center; font-weight: bold;">
        <span>预约申请</span>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form
        inline
        ref="searchFormRef"
        :model="searchData"
        style="display: flex; align-items: center;"
    >
      <div style="display: flex; align-items: center;">
        <el-form-item label="会议室：" prop="roomname">
          <el-input v-model="searchData.roomname" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="容纳人数：" prop="capacity">
          <el-select v-model="searchData.capacity" placeholder="请选择容纳人数" clearable style="width: 180px;">
            <el-option label="10人以下" value="10" :key="10"></el-option>
            <el-option label="10-30人" value="30" :key="30"></el-option>
            <el-option label="30-50人" value="50" :key="50"></el-option>
            <el-option label="50人以上" value="51" :key="51"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div style="margin-left: auto;">
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="resetForm(searchFormRef)">重置</el-button>
      </div>
    </el-form>
    <!-- 会议室列表 -->
    <el-table :data="dataInfo" style="width: 100%; text-align: center;">
      <el-table-column label="会议室号" prop="id" width="80px" align="center"></el-table-column>
      <el-table-column label="会议室名称" prop="roomname" align="center"></el-table-column>
      <el-table-column label="容纳人数" prop="capacity" width="80px" align="center"></el-table-column>
      <el-table-column label="地点" prop="location" align="center"></el-table-column>
      <el-table-column label="负责人" prop="username" width="100px" align="center"></el-table-column>
      <el-table-column label="手机号" prop="phone" align="center"></el-table-column>
      <el-table-column label="修改时间" prop="updateTime" align="center"></el-table-column>
      <el-table-column label="操作" width="80" align="center">
        <template #default="{ row }">
          <el-button
              type="primary"
              size="small"
              @click="isOpenBookWindow = true; showDialog(row)"
          >预约</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: center;"
    />

    <!-- 预约会议室弹窗 -->
    <el-dialog
        v-model="dialogVisible"
        width="750px"
        destroy-on-close
        :close-on-click-modal="false"
        :show-close="false"
    >
      <div style="text-align: center; font-size: 20px; margin-bottom: 10px;">预约信息</div>
      <el-divider></el-divider>
      <el-form
          :model="addOrEditModel"
          :rules="rules"
          ref="ruleFormRef"
          label-width="120px"
          style="padding-right: 30px; display: flex; flex-wrap: wrap; justify-content: center;"
          class="book_form"
      >
        <el-form-item label="会议室名称：" style="flex: 1 1 48%;">
          <span style="font-weight: bold;">{{addOrEditModel.roomname}}</span>
        </el-form-item>
        <el-form-item label="可容纳人数：" style="flex: 1 1 48%;">
          <span style="font-weight: bold;">{{addOrEditModel.capacity}}</span>
        </el-form-item>
        <el-form-item label="地点：" style="flex: 1 1 48%;">
          <span style="font-weight: bold;">{{addOrEditModel.location}}</span>
        </el-form-item>
        <el-form-item label="负责人：" style="flex: 1 1 48%;">
          <span style="font-weight: bold;">{{addOrEditModel.username}}</span>
        </el-form-item>
        <el-form-item label="负责人电话：" style="flex: 1 1 48%;">
          <span style="font-weight: bold;">{{addOrEditModel.phone}}</span>
        </el-form-item>
        <el-form-item label="预约时间：" prop="timeslot" style="flex: 1 1 100%;">
          <el-date-picker
              v-model="addOrEditModel.timeslot"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="活动名称：" prop="title" style="flex: 1 1 100%;">
          <el-input v-model="addOrEditModel.title" placeholder="请输入活动名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="活动申请理由：" prop="reason" style="flex: 1 1 100%;">
          <el-input v-model="addOrEditModel.reason" placeholder="请输入活动申请理由" clearable></el-input>
        </el-form-item>
        <el-form-item label="活动描述：" prop="description" style="flex: 1 1 100%;">
          <el-input v-model="addOrEditModel.description" placeholder="请输入活动描述" clearable></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: center;">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitForm(ruleFormRef)"
          > 确认预约 </el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>
<style lang="scss" scoped>


.book_form {
  ::v-deep(.el-input.el-input--suffix)  {
    width: 190px;
  }

  ::v-deep(.el-form-item__label) {
    width: 200px!important;
  }
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.el-table__row:hover {
  transform: translateY(-5px);
  transition: transform 0.3s ease;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style>